/*
 * Copyright (c) 2024 Black Sesame Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "dal_rticonnextdds/entity_impl/DalDomainParticipantImpl.hpp"

DalDomainParticipantImpl::DalDomainParticipantImpl(DDS_DomainParticipant *rti_participant,
                                                   DomainParticipantListenerImpl* listener)
{
    this->rti_participant_ = rti_participant;
    this->listener_ = listener;
    if (this->listener_)
        this->listener_->ref_count_.Increase();
}

DalDomainParticipantImpl::~DalDomainParticipantImpl()
{
    if (this->listener_)
        this->listener_->ref_count_.Decrease();
}

DDS_DomainParticipant* DalDomainParticipantImpl::RtiddsDomainParticipant()
{
    return this->rti_participant_;
}

dal_ret_t DalDomainParticipantImpl::SetDomainFromConf(DDS_DomainParticipant* domain_from_conf)
{
    if (domain_from_conf < 0) {
        return DAL_RETCODE_ERROR;
    }
    this->domain_from_conf_ = domain_from_conf;
    return DAL_RETCODE_OK;
}

dal_ret_t DalDomainParticipantImpl::DestroyDomainFromConf()
{
    return DAL_RETCODE_OK;
}

void DalDomainParticipantImpl::set_participant_monitor(std::thread &th)
{
    participant_monitor_thread_ = std::move<std::thread&>(th);
}

void DalDomainParticipantImpl::enable_participant_monitor()
{
    participant_monitor_thread_flag_.store(true);
}

using namespace std::chrono_literals;

void DalDomainParticipantImpl::disable_participant_monitor()
{
    participant_monitor_thread_flag_.store(false);
    if(participant_monitor_thread_.joinable()) {
        participant_monitor_thread_.join();
    }
}

std::atomic_bool& DalDomainParticipantImpl::get_participant_monitor_flag()
{
    return participant_monitor_thread_flag_;
}

dal_participant_monitor_callback DalDomainParticipantImpl::get_monitor_callback()
{
    return this->listener_->get_participant_monitor_callback();
}

void* DalDomainParticipantImpl::get_monitor_callback_data()
{
    return this->listener_->get_participant_monitor_callback_data();
}
